package com.zmj.framework.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zmj.framework.bean.UserSession;

public class AuthorityInterceptor implements HandlerInterceptor {
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod handlerMethod=(HandlerMethod)handler;
		String methodName=handlerMethod.getMethod().getName();
		String className=handlerMethod.getBean().getClass().getSimpleName();
		if ((className.indexOf("LoginCtrl") >= 0)) {
			return true;
		}
		UserSession userSession = (UserSession) request.getSession().getAttribute("userSession");
		if (userSession == null) {
			sendRedirect(request, response);
			return false;
		}
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	private void sendRedirect(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.sendRedirect("login.do?method=logout");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}